import axios from 'axios'
import {
  ElMessage,
  ElLoading
} from 'element-plus';
//添加响应拦截器
axios.interceptors.response.use(res => {
  //  if (res.headers.accesstoken && res.headers.accesstoken !== localStorage.getItem('token'))  {
  //   localStorage.setItem('token', res.headers.accesstoken)
  // }
  return res
}, error => {
  // 响应状态码处理
  if (error.response.status == 401) {
    ElMessage.error(error.response.data.error_msg)
  }
  if (error.response.status == 403) {
    ElMessage.error(error.response.data.error_msg)
  }
  return Promise.reject(error)
})
//添加请求拦截器
axios.interceptors.request.use(
  config => {
    // let hasAuthorization = localStorage.getItem('token') || ''
    // config.headers.AccessToken = hasAuthorization
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
class Model {
  constructor() {
    // headers = {
    //   'Content-Type': 'application/json;charset=UTF-8',
    // }
    // this.instance = axios.create({
    //   // headers: headers
    // })
  }
  api(options = {}) {
    if (!options.method) options.method = 'get'
    if (options.domain) options.url = options.domain + options.url
    return new Promise((resolve, reject) => {
      let request = axios(options)
      request
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          throw new Error(error)
        })
    })
  }

  get(options = {}) {
    options.method = 'get'
    return this.api(options)
  }

  post(options = {}) {
    options.method = 'post'
    return this.api(options)
  }

  put(options = {}) {
    options.method = 'put'
    return this.api(options)
  }

  delete(options = {}) {
    options.method = 'delete'
    return this.api(options)
  }
}
export default Model